package com.nimlib.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

class SP {
    static void saveUserAccount(Context context,NimLoginInfo info){
        if (!info.valid())return;
        SharedPreferences sp = context.getSharedPreferences("JLJ_nimlib_login", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("account",info.getAccount());
        editor.putString("token",info.getToken());
        NimLoginInfo localUser = null;
        if (!TextUtils.isEmpty(info.getAvatar())){
            localUser = getUserAccount(context);
            if (!TextUtils.equals(localUser.getAvatar(),info.getAvatar())){
                editor.putString("avatar",info.getAvatar());
            }
        }
        if (!TextUtils.isEmpty(info.getName())){
            localUser = localUser==null?getUserAccount(context):localUser;
            if (!TextUtils.equals(localUser.getName(),info.getName())){
                editor.putString("name",info.getName());
            }
        }
        if (!TextUtils.isEmpty(info.getMobile())){
            localUser = localUser==null?getUserAccount(context):localUser;
            if (!TextUtils.equals(localUser.getMobile(),info.getMobile())){
                editor.putString("mobile",info.getMobile());
            }
        }
        editor.apply();
    }

    static NimLoginInfo getUserAccount(Context context){
        SharedPreferences sp = context.getSharedPreferences("JLJ_nimlib_login", Context.MODE_PRIVATE);
        String account = sp.getString("account","");
        String token = sp.getString("token","");
        String avatar = sp.getString("avatar","");
        String name = sp.getString("name","");
        String mobile = sp.getString("mobile","");
        NimLoginInfo nimLoginInfo = new NimLoginInfo(account, token);
        nimLoginInfo.setAvatar(avatar);
        nimLoginInfo.setName(name);
        nimLoginInfo.setMobile(mobile);
        return nimLoginInfo;
    }

    public static void deleteUserAccount(Context context) {
        SharedPreferences sp = context.getSharedPreferences("JLJ_nimlib_login", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.remove("account");
        edit.remove("token");
        edit.remove("avatar");
        edit.remove("name");
        edit.remove("mobile");
        edit.apply();
    }
}
